/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.db.table;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.rails.core.db.SQLHelper;

@SuppressWarnings("serial")
public final class Columns extends ArrayList<String> {

	private final Logger logger = Logger.getLogger(this.getClass());

	private static Map<String, List<String[]>> MAPS;

	private String tableName;
	
	private DataSource dataSource;
	
	static{
		MAPS = new HashMap<String, List<String[]>>();
	}

	public Columns(DataSource dataSource,String tableName) {
		super();
		this.tableName = tableName;	
		this.dataSource = dataSource;
		initMaps();
		for (String[] s : getMaps()) {
			this.add(s[0]);
		}
	}
	
	private void initMaps() {
		if (!MAPS.containsKey(tableName)) {
			final SQLHelper sqlHelper = new SQLHelper(dataSource);
			try {
				MAPS.put(tableName, sqlHelper.getColumnMaps(tableName));
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}		
		}		
	}
	
	public List<String[]> getMaps(){
		return MAPS.get(tableName);
	}

}
